﻿using System;
using System.Drawing;
using System.IO;
using System.Transactions;
using System.Windows.Forms;
using System.Xml;
using AuthoringClientPlugIn.Properties;
using AuthoringClientPlugIn.PubService;
using Microsoft.Office.Core;
using Microsoft.Office.Interop.Word;

namespace AuthoringClientPlugIn
{
    internal partial class PublishingPane : UserControl
    {
        private readonly ThisDocument _document;

        public PublishingPane(ThisDocument document)
        {
            _document = document;
            InitializeComponent();
        }

        private void OnPublishButtonClick(object sender, EventArgs e)
        {
            if (!PopulateMetadata())
            {
                MessageBox.Show(Resources.PleaseAddBookmarksMessage);
            }
            else
            {

                object missing = System.Type.Missing;
                object fileName = "D://Testing11.docx";
                object format = WdSaveFormat.wdFormatDocumentDefault ;
               // object missing = System.Type.Missing;
                string destFileName = "Temp.docx";
                SaveProperties();
                _document.SaveAs2(ref fileName, ref format, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing,
                ref missing);

                File.Copy(fileName.ToString(), destFileName, true);
                
         
                
                IPublishingManager pubService = new PublishingManagerClient();
                var incomingData = new IncomingDocumentData {ContentType = "Document"};

                var fileStream = new FileStream(destFileName, FileMode.Open);

                using (var reader = new BinaryReader(fileStream))
                {
                    incomingData.DocumentBytes = reader.ReadBytes((int) fileStream.Length);
                }

                using (var ts = new TransactionScope())
                {
                    pubService.Publish(incomingData);
                    ts.Complete();
                }

                MessageBox.Show(Resources.PublishedMessage);
            }
        }

        private void OnMetadataButtonClick(object sender, EventArgs e)
        {
            PopulateMetadata();
        }

        public void PopulateTable()
        {
            int i = 0;

            var doc = new XmlDocument();
            doc.LoadXml(Resources.ContentType);

            foreach (XmlNode field in doc.DocumentElement.ChildNodes)
            {
                // ignore comment nodes etc.
                if (field.NodeType != XmlNodeType.Element)
                    continue;

                var txtBox = new TextBox {Name = "TxtID" + i + field.Name};

                var lbl = new Label {Name = "LblID" + i + field.Name, Text = field.Name};

                tableLayoutPanel1.Controls.Add(txtBox);
                tableLayoutPanel1.Controls.Add(lbl);
                tableLayoutPanel1.SetRow(txtBox, i);
                tableLayoutPanel1.SetRow(lbl, i);
                tableLayoutPanel1.SetColumn(lbl, 0);
                tableLayoutPanel1.SetColumn(txtBox, 1);
                tableLayoutPanel1.RowCount = i;
                tableLayoutPanel1.RowStyles.Add(new RowStyle());
                i++;
            }
            int height = tableLayoutPanel1.RowCount*50;
            tableLayoutPanel1.Size = new Size(260, height);
        }

        public bool PopulateMetadata()
        {
            bool complete = true;
            int i = 0;
            var doc = new XmlDocument();
            doc.LoadXml(Resources.ContentType);

            foreach (XmlNode field in doc.DocumentElement.ChildNodes)
            {
                if (field.NodeType != XmlNodeType.Element)
                    continue;

                bool found = false;
                string txtBoxId = "TxtID" + i + field.Name;
                var txtBox = tableLayoutPanel1.Controls.Find(txtBoxId, true)[0] as TextBox;

                foreach (Bookmark item in _document.Bookmarks)
                {
                    if (item.Name == field.Name)
                    {
                        if (!string.IsNullOrEmpty(item.Range.Text) &&
                            item.Range.Text.Trim().ToLower().Replace("\r", string.Empty) != field.Name.Trim().ToLower())
                        {
                            found = true;
                            txtBox.Text = item.Range.Text;
                            string lblId = "LBLID" + i + field.Name;
                            var lbl = tableLayoutPanel1.Controls.Find(lblId, true)[0] as Label;
                            lbl.ForeColor = Color.Black;
                            lbl.Text.Replace("*", string.Empty);
                        }
                        else if (!string.IsNullOrEmpty(txtBox.Text))
                        {
                            found = true;

                            item.Range.Text = txtBox.Text;
                        }
                    }
                }

                if (!string.IsNullOrEmpty(txtBox.Text))
                    found = true;


                if (!found)
                {
                    string lblId = "LBLID" + i + field.Name;
                    var lbl = tableLayoutPanel1.Controls.Find(lblId, true)[0] as Label;
                    lbl.ForeColor = Color.Red;
                    complete = false;
                }
                i++;
            }

            return complete;
        }

        public void SaveProperties()
        {
            //var docProperties = _document.BuiltInDocumentProperties as DocumentProperties;
            var custProperties = _document.CustomDocumentProperties as DocumentProperties;
            var doc = new XmlDocument();
            doc.LoadXml(Resources.ContentType);
            int i = 0;
            foreach (XmlNode field in doc.DocumentElement.ChildNodes)
            {
                if (field.NodeType != XmlNodeType.Element)
                    continue;

                string txtBoxId = "TxtID" + i + field.Name;
                var txtBox = tableLayoutPanel1.Controls.Find(txtBoxId, true)[0] as TextBox;

                custProperties.Add(field.Name, false, MsoDocProperties.msoPropertyTypeString, txtBox.Text, false);

                i++;
            }
        }
    }
}
